package linker

import (
	"debug/elf"
	"fmt"
	"risc-v/ld/pkg/utils"
)

type MachineType = uint8

const (
	MachineTypeNone    MachineType = iota
	MachineTypeRISCV64 MachineType = iota
)

type Machine struct {
	MachineType
}

// Strings 把MachineType 转为字符串形式
func (m Machine) Strings() string {
	switch m.MachineType {
	case MachineTypeRISCV64:
		return "riscv64"
	case MachineTypeNone:
		return "none"
	default:
		utils.Fatal(fmt.Sprintf("no support machine type %d", m.MachineType))
	}
	return "none"
}

// GetMachineTypeFromContent 判断ELF文件类型位Object文件，再读取Machine和elf.Class 确保为 RISCV64
func GetMachineTypeFromContent(content []byte) MachineType {
	fileType := GetFileType(content)
	switch fileType {
	case FileTypeObject:
		// 读取 FileHeader.Machine 即第18个字节开始的两个字节的内容
		machine := utils.Read[uint16](content[18:])
		if machine == uint16(elf.EM_RISCV) {
			class := elf.Class(content[4])
			switch class {
			case elf.ELFCLASS64:
				return MachineTypeRISCV64
			}
		}
	}

	return MachineTypeNone
}
